package com.guyu.common.core.entity;

import lombok.Getter;
import lombok.NoArgsConstructor;

import java.util.Objects;

/**
 * <p> ID分页对象 </p>
 */
@Getter
@NoArgsConstructor
public class IDPageRequest<T> implements java.io.Serializable {

    private static final long serialVersionUID = -3249240106177676069L;
    /**
     * 行ID
     * 上一页：第一条记录的ID
     * 下一页：最后一条记录的ID
     */
    private T rowId;
    /**
     * 每页显示数量[1,1000]
     */
    private int size = 10;
    /**
     * 0上一页，1下一页
     */
    private int direction = 1;

    private IDPageRequest(T rowId, int size, int direction) {
        if (size < 1) {
            throw new IllegalArgumentException("Page size must not be less than 1!");
        }
        if (size > 1000) {
            throw new IllegalArgumentException("Page size must not be greater than 1000!");
        }
        if (direction != 0 && direction != 1) {
            throw new IllegalArgumentException("Direction must be 0 or 1!");
        }

        this.rowId = rowId;
        this.size = size;
        this.direction = direction;
    }

    public static <T> IDPageRequest<T> of(T rowId, int size, int direction) {
        return new IDPageRequest<T>(rowId, size, direction);
    }

    /**
     * 上一页
     */
    public static <T> IDPageRequest<T> previous(T rowId, int size) {
        return new IDPageRequest<T>(rowId, size, 0);
    }

    /**
     * 下一页
     */
    public static <T> IDPageRequest<T> next(T rowId, int size) {
        return new IDPageRequest<T>(rowId, size, 1);
    }

    /**
     * 第一页
     */
    public static <T> IDPageRequest<T> first(int size) {
        return next(null, size);
    }

    /**
     * 最后一页
     */
    public static <T> IDPageRequest<T> last(int size) {
        return previous(null, size);
    }

    public void setRowId(T rowId) {
        this.rowId = rowId;
    }

    public void setSize(int size) {
        if (size < 1) {
            throw new IllegalArgumentException("Page size must not be less than 1!");
        }
        if (size > 1000) {
            throw new IllegalArgumentException("Page size must not be greater than 1000!");
        }
        this.size = size;
    }

    public void setDirection(int direction) {
        if (direction != 0 && direction != 1) {
            throw new IllegalArgumentException("Direction must be 0 or 1!");
        }
        this.direction = direction;
    }

    /**
     * 是否下一页
     */
    public boolean hasNext() {
        return Objects.equals(direction, 1);
    }

}
